package com.legendframework.core.utils;

import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.Plugin;

import java.lang.reflect.Constructor;

public class BukkitVersionUtils {

    /**
     * 获取当前服务器注册的指令列表
     * 引用对象
     * @return
     */
    public static CommandMap getCommandMap(){
        //根据版本获取CraftMetaBanner
        int version = 20;
        Class craftServerClass = null;
        for (int i = 0; i < version; i++) {
            try {
                craftServerClass = Class.forName("org.bukkit.craftbukkit." + BukkitVersion.getBukkitVersion().getCmsVersion(String.valueOf(i)) + ".CraftServer");
                break;
            } catch (ClassNotFoundException e) {
            }
            if (i == version - 1) {
                //getLog().error("当前服务器核心不兼容，没有找到org.bukkit.craftbukkit.%s.CraftServer的包",BukkitVersion.getBukkitVersion().getCmsVersion("?"));
                return null;
            }
        }
        try {
            return (CommandMap) craftServerClass.getMethod("getCommandMap").invoke(Bukkit.getServer());
        } catch (Exception e) {
            //getLog().error("当前服务器核心不兼容，没有找到%s下的getCommandMap方法",craftServerClass.getName());
            return null;
        }
    }

    /**
     * 实例化PluginCommand
     * @param cmd 根指令
     * @param plugin 主类
     * @return
     */
    public static PluginCommand createCommand(String cmd , Plugin plugin){
        try {
            Class<?> pluginCommandClass = Class.forName("org.bukkit.command.PluginCommand");

            Constructor<?> declaredConstructor = pluginCommandClass.getDeclaredConstructor(String.class, Plugin.class);

            declaredConstructor.setAccessible(true);

            return (PluginCommand) declaredConstructor.newInstance(cmd,plugin);
        } catch (Exception e) {
            //getLog().error("实例化PluginCommand失败");
            return null;
        }
    }
    
}
